<template>
<div>
	<div class="table">
		<row>
		    <div class="divmenu">
			    <Col :lg="{span:2}" :md="{span:8}" :sm="{span:10}" :xs="{span:20}">
				     <Button type="primary"  size="large" @click="Add">
					     <p class="title">
						     <Icon type="plus-circled" size="20"></Icon>&nbsp;&nbsp;<span>新增</span>
					     </p>
				     </Button>
			     </Col>
		    </div>
	    </row>
		<div class="divSearch"><!--搜索框-->
			<Row>
				<Col :lg="{span:5}" :md="{span:8}" :sm="{span:16}" :xs="{span:22}">
					<label class="searchLabel">角色名称:</label>
					<Input type="text" v-model="SearchModel.RoleName"  placeholder="请填写" class="searchInput"></Input>			
				</Col>  
				<Col :lg="{span:5}" :md="{span:8}" :sm="{span:16}" :xs="{span:22}">
					<label class="searchLabel">角色类型:</label>
					<Select v-model="SearchModel.RoleType" placeholder="请选择" class="searchInput" >
						<Option value="">全部</Option>
                		<Option :value="item.DictValue" v-for="item in RoleTypeList" :key="item.DictValue">{{item.DictText}}</Option>
					</Select>								
				</Col>   
				<Col :lg="{span:5}" :md="{span:8}" :sm="{span:16}" :xs="{span:22}">
					<label class="searchLabel">角色状态:</label>
					<Select v-model="SearchModel.Status" placeholder="请选择" class="searchInput">
						<Option value="">全部</Option>                    
						<Option value="1">启用</Option>
						<Option value="0">禁用</Option>
					</Select>								
				</Col> 
				<Col :lg="{span:2}" :md="{span:2}" :sm="{span:2}" :xs="{span:2}">
					<Button icon="ios-search" type="primary" @click="Search()" class="searchButton">查询</Button>
				</Col>      
			</Row>
		</div>
		<!--数据表格-->
		<Row>
            <Col span="24" class="col-margin">
            <Table size="large" @on-select="selectSingel" @on-select-all="selectAll" :height="clientHeight" border :context="ctx" :columns="columnsTableList" :data="datas.rows" no-data-text='暂无数据...'></Table>
            </Col>
        </Row>		
		<Row><!--分页插件-->      
				<Col>
					<!-- <spin size="large"></spin> -->
					<Page class="pageComponent" :total="datas.total" show-elevator show-sizer show-total placement="top"   @on-change="changePage">
					</Page>
				</Col>
		</Row>
    </div>
    <!--角色编辑框-->
     <Modal v-model="EditModal"  :mask-closable="false">
	    <p slot="header"  class="title"> 
			<Icon type="ios-paper" size="20"></Icon>    
            <span style="font-size: 20px">系统角色编辑</span>
        </p>
		<Form ref="RoleModel" :model="RoleModel" :rules="RoleRule" :label-width="80">
			<Form-item label="角色名称" prop="RoleName">
				<Input v-model="RoleModel.RoleName" placeholder="请输入角色名称"></Input>
			</Form-item>
			<Form-item label="角色类型" prop="RoleType">
				<Select v-model="RoleModel.RoleType" placeholder="请选择角色类型">
					<Option :value="item.DictValue" v-for="item in RoleTypeList" :key="item.DictValue">{{item.DictText}}</Option>
				</Select>
			</Form-item>
			<Form-item label="角色状态" prop="Status">
				<Select v-model="RoleModel.Status" placeholder="请选择角色状态">
					<Option value="1">启用</Option>
					<Option value="0">禁用</Option>
				</Select>
			</Form-item>
			<Form-item label="角色序号" prop="Sort">
				<Input v-model="RoleModel.Sort" placeholder="请输入角色序号"></Input>
			</Form-item>
			<Form-item label="角色描述" prop="Remark">
				<Input v-model="RoleModel.Remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入角色描述"></Input>
			</Form-item>
		</Form>
	    <div slot="footer">	
                <Button  @click="cancel('RoleModel')">取消</Button>&nbsp;&nbsp;
                <Button  type="primary"   @click="handleSubmit('RoleModel')">提交</Button>
        </div>
    </Modal>

	<!--角色授权-->
	<Modal v-model="TreeModal" :closable="false" :styles="{width: '900px'}">
		<p slot="header" class="title">
			<Icon type="ios-paper" size="20"></Icon>
			<span style="font-size: 18px">角色授权</span>
		</p>
		<div slot="footer">
			<!--<Button  @click="CloseTreeMoal()">取消</Button>&nbsp;&nbsp;
			<Button  type="primary"   @click="Authorized">提交</Button>-->
			<Button type="primary" @click="Authorized">提交</Button>
			<Button type="ghost" @click="CloseTreeMoal()" style="margin-left: 8px">取消</Button>
		</div>
		<Row>
			<Col span="10">
				<div style="text-align: center;font-size:18px;">
					<B>功能列表</B>
				</div>
				<div style="height:600px;overflow-y:auto;border: 1px solid #F0F0F0;padding: 10px;">
					<Tree :data="menuTreeData" :check-strictly="true" show-checkbox @on-check-change="treeCheckChange" @on-select-change="treeSelctChange"></Tree>
				</div>
			</Col>
			<Col span="14">
				<Row style="padding:2px 0 0 15px;">
					<Col style="font-size:18px;"> 
						<B>操作列表</B>
					</Col>
				</Row>
				<Row style="padding:2px 0px 5px 15px;">
					<Col>
						<Table :columns="columnsList" :data="menuActionData" size="small" @on-selection-change="selecChange" @on-select-all="selectAllMenu"></Table>
					</Col>
				</Row>
			</Col>
		</Row>
	</Modal>
</div>
</template>
<script>
export default {
	data(){
		return {
			self:this,
			tableTotal:0,//表格记录条数
	        EditModal:false,//数据编辑modal开关,针对form填报表格
			TreeModal:false,//角色授权modal开关
	        showCollapse:1,//显示的手风琴项
			clientHeight:window.innerHeight-340,//数据表格高度
			menuTreeData: [],
			MenuRoleActionList: [],//操作权限：选择菜单保存{角色编号、菜单编号、操作编号}
			MRIdList: [],//全部权限：全部所选权限列表{角色编号、菜单编号、操作编号}
			MenuRoleList: [],//菜单权限：选择菜单保存{角色编号、菜单编号、''}
			menuActionData: [],//菜单操作列表
			SearchModel:{
				PageNumber:1,//页码
				PageSize:20,//页面数量
				RoleName:'',RoleType:'',Status:''
			},
			RoleTypeList:this.GetGroupDict("RoleType"),//角色类型
	        RoleModel: {//V-model
				Id:0,RoleName:'',RoleType:'',Status:'',Sort:'',Remark:''
	        },
	        //表单验证规则
	        RoleRule: {//表单验证规则
				RoleName:[ { required: true, message: '请填写角色名称', trigger: 'blur' }],
	        	RoleType:[ { required: true, message: '请选择角色类型', trigger: 'change' }],
	        	Status:[ { required: true, message: '请选择角色状态', trigger: 'change' }],
				Sort:[ { required: true, message: '请填写排序号', trigger: 'blur' }],
		        Remark:[ { required: true, message: '请填写描述', trigger: 'blur' }],
	        },
			columnsList: [//表头对象
                { type: 'selection', width: 60, align: 'center' },//多选设置
                { title: "操作地址", key: "CtrlUrl" },
                { title: "操作名称", key: "ActionName" },
                { title: "代码", key: "ActionCode" }
            ],
			datas: {},//table数据对象
			ctx: this,//table数据上下文
			columnsTableList: [//表头对象
                //{ type: 'selection', width: 60, align: 'center' },//多选设置
                { title: "名称", key: "RoleName"},
                { title: "角色类型", key: "RoleTypeName" },
                { title: "状态", key: "StatusName" },
                { title: "排序", key: "Sort" },
                { title: "备注", key: "Remark" },
				 {title: '操作',key: 'action',width: 300,align: 'center',
					render:(h,params)=>{
						return h('div', [
											h('Button', { class:{ieditColor:true},props: {type:'ghost',size:'small',icon:'pull-request'},style: {marginRight: '5px'},on: {click: () => {this.ShowTreeModal(params.row.Id) }}}, '授权'),
											h('Button', { class:{ieditColor:true},props: {type:'ghost',size:'small',icon:'ios-compose'},style: {marginRight: '5px'},on: {click: () => {this.Edit(params.row.Id) }}}, '编辑'),
											h('Button', { class:{ideleteColor:true},props: {type:'ghost',size:'small',icon:'ios-trash-outline'},on: {click: () => {this.Remove(params.row.Id); }}}, '删除')])
	                }
				}		
			]
		}
	},
	mounted:function(){
		 const that = this;
			window.onresize = () => {
				return (() => {
					that.clientHeight = window.innerHeight-340;
				})()
			};
	},
	methods:{
		selectChange(node){
		},
		//查询方法
		Search() {
			this.initTableData();
		},
		Add:function(){//添加数据
			this.showModel();//打开弹窗
		},
        showModel:function(){
            this.EditModal=true;//显示对话框      
        },
		//-------------------------------------------------------数据新增编辑-----------------------------------------
        handleSubmit (name) {//数据提交
			var self=this;
			self.$refs[name].validate((valid) => {
					if (valid) {
							if(self.RoleModel.Id==0){
								self.$http.post('Role',self.RoleModel).then(
									function(res){
										if(res.data.status===1)
										{
											self.initTableData();
											self.restModel(name);//重置model
											self.$Modal.success( {title:"提示信息",content:"角色信息添加成功"});
											self.EditModal=false;
										}
										else{
											self.$Modal.warning( {title:"提示信息",content:"角色信息添加失败,请与管理员联系!"});
										}
									});		
							}
							else{
								self.$http.put('Role',self.RoleModel).then(
								function(res){
									if(res.data.status==1)
									{
										self.initTableData();
										self.restModel(name);//重置model
										self.$Modal.success( {title:"提示信息",content:"数据编辑成功"});
										self.RoleModel.Id=0;//Id归零
										self.EditModal=false;
										self.initTableData();
									}
									else{
										self.$Modal.warning( {title:"提示信息",content:"数据编辑失败,请与管理员联系!"});
									}
								});
							}
					} 
			});
		},
			//---------------------------------------------------------------------------------------------------------------------------
		cancel:function(name){//关闭新增对话框
			this.$refs[name].resetFields();//关闭表单校验
			this.EditModal=false;//关闭对话框
		},
            //批量删除
		Removes:function(id,index){//批量删除
			this.$Modal.confirm({
				title: '提示信息',
				content: '<p>数据删除后不可恢复，确定要删除？</p>',
				onOk: () => {
					this.tabledata=[];
					this.$Message.info('数据删除成功');
					this.tableTotal=this.tabledata.length;
				}
			});
		},
		Remove :function(ID) {//删除单条数据
			var  self=this;
			self.$Modal.confirm({
				title: '提示信息',
				content: '<p>数据删除后不可恢复，确定要删除？</p>',
				onOk: () => {
					this.$http.delete("Role",{ params: { id: ID } }).then(
						function(res){
							if(res.data.status==1)
							{
								self.$Modal.success({title:"提示信息",content:"数据删除成功!!!"});
								self.initTableData();
							}
							else{
								self.$Modal.error({title:"提示信息",content:"数据删除失败!!!"});
							}
						}
					)
				}
			});             
		},
		Edit:function(ID){//编辑数据
			var self=this;
			this.$http.get("Role",{ params: { id: ID } }).then(//获取数据编辑项的值
				function(res){
					if(res.data.status==1)
					{
						
						self.RoleModel=res.data.model;
						self.RoleModel.Id=ID;
					}
					else{
						self.$Modal.error({title:"提示信息",content:"编辑数据加载失败!!!"});
					}
				}
			)            
			this.showModel();
		},
		//--------------------------------角色授权----------------------------------------------------------------
		ShowTreeModal:function(RoleID){//显示树状菜单
			this.TreeModal=true;
			var self=this;
			self.RoleModel.Id=RoleID;
			this.$http.get("role/GetMRTreeList", { params: { id: RoleID } }).then(function (res) {
				if (res.data.status == 1) {
					self.menuTreeData = res.data.model;
				}
				else {
					self.$Modal.error({ title: "提示信息", content: "树形菜单初始化失败!!!" });
				}
            });
			this.$http.get("MenuRole/GetList", { params: { id: RoleID } }).then(function (res) {
				if (res.data.status == 1) {
					self.MenuRoleActionList = res.data.model;
				}
				else {
					self.$Modal.error({ title: "提示信息", content: "角色菜单权限获取失败!!!" });	
				}	
			});
		},
		CloseTreeMoal:function(){//关闭树状菜单
			this.TreeModal=false;	
			self.menuTreeData = [];
            this.RoleId = "";
            this.MenuId = "";
            this.MRIdList = [];
            this.MenuRoleList = [];
            this.MenuRoleActionList = [];
            this.menuActionData = [];
		},
		checkChange:function(obj){//获取当前选中的节点
			this.AuthorizeData=[];
			for(var i=0;i<obj.length;i++)
			{
				this.AuthorizeData.push(obj[i].Id);
			}
		},
		//obj为当前选中的项目，数组的形式
		Authorized:function(){//角色授权(提交数据)
			var self=this;
			this.MRIdList = this.MenuRoleList;
            //删除操作权限
            this.DelActionList();
			//添加操作权限
            for (var i = 0; i < this.MenuRoleActionList.length; i++) {
                this.MRIdList.push(this.MenuRoleActionList[i]);
            }
			var model = new Object();
            model.RoleId = self.RoleModel.Id;
            model.MRList = this.MRIdList;
            this.$http.post("MenuRole/Post", model).then(function (res) {
				if (res.data.status == 1) {
					self.$Notice.success({ title: '授权成功！', desc: false });
					self.TreeModal=false;
				}
				else {
					self.$Modal.error({ title: "提示信息", content: "授权失败!" });
				}
			});
		},
		//全选方法
        selectAllMenu(selection) {
            this.getRoleMenuActionIdList(selection);
        },
		//checkbox取消选中方法
        selecChange(selection) {
            this.getRoleMenuActionIdList(selection);
        },
		//设置对应的操作权限
        getRoleMenuActionIdList(selection) {
            //删除指定菜单的操作权限
            this.DelMenuList(this.MenuId);
            if (selection.length !== 0) {
                for (var i = 0; i < selection.length; i++) {
                    //增加操作权限
                    this.MenuRoleActionList.push({ RoleId: this.RoleModel.Id, MenuId: selection[i].MenuId, ActionId: selection[i].Id });
                }
            }
        },
		//删除对应菜单的操作权限
        DelMenuList(menuid) {
            for (var i = 0; i < this.MenuRoleActionList.length; i++) {
                var obj = this.MenuRoleActionList[i];
                if (obj.MenuId == menuid) {
                    this.MenuRoleActionList.splice(i, 1);
                    i--;
                }
            }
        },
		DelActionList() {
            for (var i = 0; i < this.MRIdList.length; i++) {
                var obj = this.MRIdList[i];
                if (obj.ActionId != "") {
                    this.MRIdList.splice(i, 1);
                    i--;
                }
            }
        },
		//树的checkbox选择事件
        treeCheckChange(obj) {
            this.MenuRoleList = [];
            if (obj.length !== 0) {
                for (var i = 0; i < obj.length; i++) {
                    this.MenuRoleList.push({ RoleId: this.RoleModel.Id, MenuId: obj[i].Id, ActionId: "" });
                    if (obj[i].ParentId != "") {
                        //检查父级是否存在,不存在则新增
                        if (!this.CheckParentMenu(obj[i].ParentId)) {
                            this.MenuRoleList.push({ RoleId: this.RoleModel.Id, MenuId: obj[i].ParentId, ActionId: "" });
                        }
                    }
                }
            }
        },
		//检查父级是否存在
        CheckParentMenu(parentid) {
            for (var i = 0; i < this.MenuRoleList.length; i++) {
                if (parentid == this.MenuRoleList[i].MenuId && parentid != "") {
                    return true;
                }
            }
        },
		//获取操作权限列表
        treeSelctChange(obj) {
            var self = this;
            //设置当前的菜单ID
            this.MenuId = obj[0].Id;
            this.$http.get("MenuAction/GetList", { params: { id: this.MenuId } })
                .then(function (res) {
                    if (res.data.status == 1) {
                        self.menuActionData = res.data.model;
                        for (var i = 0; i < self.menuActionData.length; i++) {
                            //判定是否存在，存在选中，不存在不选中
                            if (self.CheckMenuAction(self.menuActionData[i].MenuId, self.menuActionData[i].Id)) {
                                //查看iview的table api
                                self.menuActionData[i]._checked = true;
                            } else {
                                self.menuActionData[i]._checked = false;
                            }
                        }
                    }
                    else {
                        self.$Modal.error({ title: "提示信息", content: "数据删除失败!!!" });
                    }
                });
        },
		//验证操作权限是否选中
        CheckMenuAction(menuid, actionid) {
            for (var i = 0; i < this.MenuRoleActionList.length; i++) {
                var obj = this.MenuRoleActionList[i];
                if (obj.MenuId == menuid && obj.ActionId == actionid) {
                    return true;
                }
            }
        },
		//重置model
        restModel(modelname) {
            this.$refs[modelname].resetFields();//重置model
        },
			//----------------------------------------------------------------------------------------------------------
            //全选
		selectAll:function(){
			alert("全选");
		},
            //单选
		selectSingel:function(){
			alert("单选");
		},
		exportData:function(){
			this.$refs.table.exportCsv({
					filename: '原始数据'
				});
		},
		initTableData:function(){//初始化数据
			var self=this;
			this.$http.post("Role/PostPageList",this.SearchModel).then(function(res){
				if (res.data.status === 1) {
                    self.datas = res.data;
                }
                else {
                    self.$Modal.error({ title: '提示信息', content: res.data.message });
                }
			})
		},
		changePage:function(pageIndex){//改变页码事件
			this.SearchModel.PageNumber=pageIndex;
			this.initTableData();
		},
		changePageSize:function(pageSize){//改变页面记录条数事件
			this.SearchModel.PageSize=pageSize;
			this.initTableData();
		}
	},
	created:function(){ //初始化函数
		this.initTableData();
	}
}
</script>